﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using Network;
using Network.Messages.LiveControl;

namespace Providers.LiveControl.Server.ScreenHelper
{
   public class GridNodeManager
    {
       readonly List<GridNodeTree> _gridNodeTrees = new List<GridNodeTree>();

       public GridNodeManager()
       {
           UpdateNodeTreeCount();
       }

       public void UpdateNodeTreeCount()
       {
           int count = Screen.AllScreens.Length;
           int currentCount = _gridNodeTrees.Count;
           if (_gridNodeTrees.Count< count)
           {
               for (int i = currentCount; i < count; i++)
               {
                    _gridNodeTrees.Add(new GridNodeTree(i));
               }
           }
       }

       public void Test()
       {
            _gridNodeTrees[1].RequestNewScreen();
        }
       public void SendScreens(NetworkPeer network,
           Dictionary<IPEndPoint, MessageEventArgs<RequestScreenshotMessage>> dicMessages)
        {
            UpdateNodeTreeCount();
            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                var messages = dicMessages.Values.Where(args => args.Message.ScreenIndex == i).ToList();
                if (messages.Count == 0)
                {
                    continue;
                }
                _gridNodeTrees[i].RequestNewScreen();
                
                //_gridNodeTrees[i].SendScreen(network, messages);
                _gridNodeTrees[i].SendScreenInnerLoop(network, messages);

                foreach (var messageEventArgse in messages)
                {
                    messageEventArgse.Message.Resolve = true;
                }
               
            }
       }
    }
}
